package com.ben.multiple.mycat.two;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@Slf4j
@AllArgsConstructor
@RestController
@RequestMapping("/company")
public class CompanyResource {
    private final CompanyService companyService;

    @PostMapping("/insert")
    public ResponseEntity<Boolean> insertCompany(@RequestBody Company model) {
        boolean save = companyService.save(model);
        return ResponseEntity.ok(save);
    }

    @PostMapping("/insert/batch")
    public ResponseEntity<Boolean> insertBatchCompany(@RequestBody List<Company> model) {
        int size = model.size();
        long start = System.currentTimeMillis();
        boolean save = companyService.saveBatch(model);
        long end = System.currentTimeMillis();
        log.info("insertBatchCompany, size:{}, time:{}", size, end - start);
        return ResponseEntity.ok(save);
    }

    @GetMapping("/list")
    public ResponseEntity<List<Company>> listCompany(@RequestParam(name = "search", required = false) String search) {
        LambdaQueryWrapper<Company> wrapper = Wrappers.<Company>lambdaQuery().orderByDesc(Company::getCreateTime)
                .nested(StringUtils.hasText(search),
                        i -> i.like(Company::getName, search).or().like(Company::getCorporation, search));
        long start = System.currentTimeMillis();
        List<Company> list = companyService.list(wrapper);
        long end = System.currentTimeMillis();
        int size = list.size();
        log.info("listCompany, size:{}, time:{}", size, end - start);
        return ResponseEntity.ok(list);
    }

}
